package com.woniu.day8.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.day8.mapper.UserInfoMapper;
import com.woniu.day8.pojo.UserInfo;
import com.woniu.day8.pojo.dto.UserInfoDto;
import com.woniu.day8.service.UserInfoService;
import com.woniu.day8.util.ResultMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Autowired
    private UserInfoMapper UserInfoMapper;
    /**
     * 用户登录方法
     */
    @Override
    public ResultMessage login(UserInfo UserInfo) {
        //1.根据用户名进行查询用户信息
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<UserInfo>();
        //添加查询条件
        wrapper.eq("username", UserInfo.getUsername());
        UserInfo user = UserInfoMapper.selectOne(wrapper);
        if(user.getIsdelete()==1){
            return ResultMessage.fail("用户已被封禁", 531, user);
        }
        if (user != null) { //表示查询到指定用户
            //对用户输入密码进行加密
            String md5Pwd = DigestUtils.md5DigestAsHex(UserInfo.getPassword().getBytes());
            //判断用户密码是否正确
            if(user.getPassword().equals(md5Pwd)){
                //表示密码相同
                return ResultMessage.success(user);
            }
        }
        return ResultMessage.fail("用户名或密码错误", 530, user);
    }
    @Override
    public List<UserInfo> selectUserByConditions(Page<UserInfo> page, UserInfo conditions) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();

        // 添加查询条件
        if (conditions.getId() != null) {
            queryWrapper.eq("id", conditions.getId());
        }
        if (conditions.getUsername() != null && !conditions.getUsername().isEmpty()) {
            queryWrapper.like("username", conditions.getUsername());
        }
        if (conditions.getType() != null) {
            queryWrapper.eq("type", conditions.getType());
        }
        if (conditions.getIsdelete() != null) {
            queryWrapper.eq("isdelete", conditions.getIsdelete());
        }

        // 使用自定义的queryUsers方法查询用户及其角色信息
        List<UserInfo> list = UserInfoMapper.queryUsers(page, queryWrapper);
        return list;
    }



}
